<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name" v-if="!showView">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" v-if="!showView">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery" v-if="!showView">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" v-if="!showView" plain @click="openForm('create')"
          v-hasPermi="['business:report-view:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="danger" v-if="!showView" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button>
        <el-button type="success" plain @click="changeView">
          <Icon icon="ep:sort" class="mr-5px" /> 视图切换
        </el-button>
        <el-button v-if="!showView" type="danger" plain :disabled="checkedIds.length === 0" @click="handleDeleteBatch"
          v-hasPermi="['business:report-view:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap v-if="!showView">
    <el-table v-loading="loading" :data="list" row-key="id" :default-expand-all="isExpandAll" v-if="refreshTable"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="title" label="描述" />
      <!-- <el-table-column prop="icon" label="图标" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" :formatter="dateFormatter" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('edit', scope.row.id)"
            v-hasPermi="['business:report-view:update']">
            修改
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-hasPermi="['business:report-view:delete']">
            删除
          </el-button>
          <el-button :disabled="!scope.row.url" link type="success" @click="onNodeClick(scope.row)">
            查看
          </el-button>

          <el-button :disabled="!scope.row.url" link type="success" @click="test(scope.row.id)">
            消息推送测试
          </el-button>

        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <treeView v-if="showView" />

  <!-- 表单弹窗：添加/修改 -->
  <ReportViewForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'

import { ReportViewApi } from '@/api/business/reportview'

import ReportViewForm from './ReportViewForm.vue'

import treeView from './treeView.vue'

defineOptions({ name: 'ReportView' })


const test = (id) => {
  ReportViewApi.senComdMessage(id)
}

const onNodeClick = (node: any) => {
  console.log('左键单击', node.url)

  // 检查是否存在有效URL
  if (node.url) {
    // 处理URL格式（自动补全http协议）
    const formattedUrl = node.url.startsWith('http') ? node.url : `https://${node.url}`

    // 新窗口打开（带安全限制解除）
    const newWindow = window.open('', '_blank')
    if (newWindow) {
      newWindow.opener = null  // 安全措施
      newWindow.location.href = formattedUrl
    } else {
      message.error('弹出窗口被浏览器阻止，请检查浏览器设置')
    }
  }
}

const showView = ref(true)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  name: undefined,
  status: undefined,
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReportViewApi.getReportViewPage(queryParams)
    list.value = handleTree(data.list)
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 切换视图 */
const changeView = () => {
  showView.value = !showView.value

  if (!showView.value) {
    getList()
  }

}


/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReportViewApi.deleteReportView(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除按钮操作 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (rows: ReportViewApi.ReportView[]) => {
  checkedIds.value = rows.map((row) => row.id)
}

const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起批量删除
    await ReportViewApi.deleteReportViewList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 获取用户列表
})
</script>
